<template>
  <div class="custom-script-modal-backdrop" @click="$emit('close')">
    <div class="custom-script-modal" @click.stop>
      <div class="modal-header">
        <h3>自定义剧本</h3>
        <button @click="$emit('close')" class="close-btn">&times;</button>
      </div>

      <div class="modal-content">
        <div class="custom-script-description">
          <p>加载自定义剧本配置。你可以从文件上传、URL链接或剪贴板加载剧本。</p>
          <p>推荐使用 <a href="https://script.bloodontheclocktower.com/" target="_blank">Script Tool</a> 创建剧本。</p>
          <p><strong>注意：仅加载来自可信来源的剧本文件。</strong></p>
        </div>

        <div class="popular-scripts">
          <h4>热门剧本</h4>
          <ul class="scripts-list">
            <li
              v-for="(script, index) in popularScripts"
              :key="index"
              @click="loadFromURL(script[1])"
              class="script-item"
            >
              {{ script[0] }}
            </li>
          </ul>
        </div>

        <input
          type="file"
          ref="fileInput"
          accept="application/json"
          @change="handleFileUpload"
          style="display: none"
        />

        <div class="action-buttons">
          <button @click="openFileUpload" class="action-btn upload-btn">
            <span class="icon">📁</span>
            上传文件
          </button>
          <button @click="loadFromURL()" class="action-btn url-btn">
            <span class="icon">🔗</span>
            从URL加载
          </button>
          <button @click="loadFromClipboard" class="action-btn clipboard-btn">
            <span class="icon">📋</span>
            从剪贴板加载
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CustomScriptModal",
  data() {
    return {
      popularScripts: [
        [
          "Deadly Penance Day",
          "https://gist.githubusercontent.com/bra1n/0337cc44c6fd2c44f7589256ed5486d2/raw/16be38fa3c01aaf49827303ac80577bdb52c0b25/penanceday.json",
        ],
        [
          "Catfishing 11.1",
          "https://gist.githubusercontent.com/bra1n/8a5ec41a7bbf945f6b7dfc1cef72b569/raw/a312ab93c2f302e0ef83c8b65a4e8e82760fda3a/catfishing.json",
        ],
        [
          "On Thin Ice (Teensyville)",
          "https://gist.githubusercontent.com/bra1n/8dacd9f2abc6f428331ea1213ab153f5/raw/0cacbcaf8ed9bddae0cca25a9ada97e9958d868b/on-thin-ice.json",
        ],
        [
          "Race To The Bottom (Teensyville)",
          "https://gist.githubusercontent.com/bra1n/63e1354cb3dc9d4032bcd0623dc48888/raw/5acb0eedcc0a67a64a99c7e0e6271de0b7b2e1b2/race-to-the-bottom.json",
        ],
      ],
    };
  },
  methods: {
    openFileUpload() {
      this.$refs.fileInput.click();
    },
    
    handleFileUpload() {
      const file = this.$refs.fileInput.files[0];
      if (file && file.size) {
        const reader = new FileReader();
        reader.addEventListener("load", () => {
          try {
            const roles = JSON.parse(reader.result);
            this.parseAndSelectScript(roles);
          } catch (e) {
            alert("读取剧本文件失败: " + e.message);
          }
          this.$refs.fileInput.value = "";
        });
        reader.readAsText(file);
      }
    },

    async loadFromURL(url) {
      if (!url) {
        url = prompt("请输入剧本JSON文件的URL:");
      }
      if (url) {
        try {
          const response = await fetch(url);
          if (response && response.ok) {
            const script = await response.json();
            this.parseAndSelectScript(script);
          } else {
            alert("无法从URL加载剧本");
          }
        } catch (e) {
          alert("加载剧本失败: " + e.message);
        }
      }
    },

    async loadFromClipboard() {
      try {
        const text = await navigator.clipboard.readText();
        const roles = JSON.parse(text);
        this.parseAndSelectScript(roles);
      } catch (e) {
        alert("从剪贴板读取剧本失败: " + e.message);
      }
    },

    parseAndSelectScript(roles) {
      if (!roles || !roles.length) {
        alert("无效的剧本数据");
        return;
      }

      // 转换角色数据格式
      roles = roles.map((role) =>
        typeof role === "string" ? { id: role } : role
      );

      // 查找元数据
      const metaIndex = roles.findIndex(({ id }) => id === "_meta");
      let meta = {};
      if (metaIndex > -1) {
        meta = roles.splice(metaIndex, 1).pop();
      }

      // 发送选中的剧本数据
      this.$emit("script-selected", {
        roles,
        meta,
        isCustom: true
      });

      // 关闭模态框
      this.$emit("close");
    },
  },
};
</script>

<style scoped lang="scss">
.custom-script-modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.custom-script-modal {
  background: linear-gradient(135deg, #2a2a2a 0%, #1a1a1a 100%);
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  border: 1px solid rgba(255, 215, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);

  h3 {
    margin: 0;
    color: #ffd700;
    font-size: 20px;
    font-weight: 600;
  }

  .close-btn {
    background: none;
    border: none;
    color: #ccc;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
      color: #fff;
    }
  }
}

.modal-content {
  padding: 24px;
}

.custom-script-description {
  margin-bottom: 24px;
  color: #ccc;
  line-height: 1.6;

  p {
    margin: 0 0 12px 0;
  }

  a {
    color: #ffd700;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  strong {
    color: #ff6b6b;
  }
}

.popular-scripts {
  margin-bottom: 24px;

  h4 {
    color: #ffd700;
    margin: 0 0 12px 0;
    font-size: 16px;
  }

  .scripts-list {
    list-style: none;
    padding: 0;
    margin: 0;

    .script-item {
      padding: 8px 12px;
      background: rgba(255, 255, 255, 0.05);
      margin-bottom: 4px;
      border-radius: 6px;
      color: #ccc;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(255, 215, 0, 0.1);
        color: #ffd700;
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;

  .action-btn {
    flex: 1;
    min-width: 120px;
    padding: 12px 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;

    .icon {
      font-size: 16px;
    }

    &.upload-btn {
      background: rgba(76, 175, 80, 0.2);
      color: #4caf50;
      border: 1px solid rgba(76, 175, 80, 0.3);

      &:hover {
        background: rgba(76, 175, 80, 0.3);
        color: #fff;
      }
    }

    &.url-btn {
      background: rgba(33, 150, 243, 0.2);
      color: #2196f3;
      border: 1px solid rgba(33, 150, 243, 0.3);

      &:hover {
        background: rgba(33, 150, 243, 0.3);
        color: #fff;
      }
    }

    &.clipboard-btn {
      background: rgba(255, 152, 0, 0.2);
      color: #ff9800;
      border: 1px solid rgba(255, 152, 0, 0.3);

      &:hover {
        background: rgba(255, 152, 0, 0.3);
        color: #fff;
      }
    }
  }
}

/* 自定义滚动条 */
.custom-script-modal::-webkit-scrollbar {
  width: 8px;
}

.custom-script-modal::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.custom-script-modal::-webkit-scrollbar-thumb {
  background: rgba(255, 215, 0, 0.3);
  border-radius: 4px;

  &:hover {
    background: rgba(255, 215, 0, 0.5);
  }
}
</style>